<template>
  <!-- 聊天记录对话框（仅保留弹窗核心） -->
  <el-dialog
    v-model="showChatHistory"
    title="聊天记录"
    width="80%"
    :close-on-click-modal="false"
    class="chat-history-dialog"
    @open="fetchChatHistory"
  >
    <div class="chat-history-content">
      <!-- 角色卡信息（从接口数据渲染） -->
      <div class="role-card-info" v-if="currentChat">
        <h3>角色卡：{{ currentChat.roleCard || '未设置' }}</h3>
        <p v-if="currentChat.remark">备注：{{ currentChat.remark }}</p>
      </div>

      <!-- 消息列表（加载状态/空状态/正常列表） -->
      <div class="messages-container" ref="messagesContainerRef">
        <!-- 加载中 -->
        <div class="loading-state" v-if="loading">
          <Loading class="loading-icon" />
          <span class="loading-text">加载聊天记录中...</span>
        </div>
        <!-- 空状态：加载完成且无数据 -->
        <div class="empty-state" v-else-if="!loading && (!currentChat || !currentChat.messages || currentChat.messages.length === 0)">
          <span>暂无聊天记录</span>
        </div>
        <!-- 正常消息列表：加载完成且有数据（明确条件，替代v-else） -->
        <div v-else>
          <div 
            v-for="(msg, index) in currentChat.messages" 
            :key="index" 
            class="message-item"
            :class="{ 'user-message': msg.sender === 'user', 'ai-message': msg.sender === 'ai' }"
          >
            <!-- 消息内容（不变） -->
                      <!-- 发送者标识 -->
            <div class="sender-info">
              <span class="sender-name">{{ msg.sender === 'user' ? '我' : currentChat.roleCard || 'AI' }}</span>
              <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
            </div>

            <!-- 消息内容和播放按钮 -->
            <div class="message-content">
              <div class="message-bubble">
                <p class="message-text">{{ msg.content }}</p>
                <el-button 
                  size="small" 
                  type="primary" 
                  plain 
                  @click="playAudio(msg.audioUrl)"
                  :disabled="!msg.audioUrl"
                  class="play-button"
                >
                  <el-icon><VideoPlay /></el-icon>
                  播放
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>



      
    </div>

    <template #footer>
      <el-button @click="showChatHistory = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch,nextTick } from 'vue'
import { ElDialog, ElButton } from 'element-plus'

import { VideoPlay } from '@element-plus/icons-vue'
// 引入接口请求函数（需替换为你的实际接口路径）
//import { getChatHistoryById } from '@/api/chat'

// 1. 接收父组件传入的会话ID
const props = defineProps({
  chatId: {
    type: [Number, String], // 支持数字/字符串类型的ID
    required: true, // 会话ID为必传项
    default: null
  },
  // 控制弹窗显示的外部开关（可选，父组件可同步控制）
  visible: {
    type: Boolean,
    default: false
  }
})

// 2. 子组件内部状态
const showChatHistory = ref(props.visible) // 弹窗显示状态
const currentChat = ref(null) // 当前会话数据（接口返回）
const loading = ref(false) // 加载状态
const messagesContainerRef = ref() // 消息容器引用

// 3. 监听父组件传入的visible，同步弹窗状态
watch(() => props.visible, (newVal) => {
  showChatHistory.value = newVal
})

// 4. 向父组件同步弹窗状态（可选）
const emit = defineEmits(['update:visible'])
watch(showChatHistory, (newVal) => {
  emit('update:visible', newVal)
})

// 5. 请求后台获取聊天记录（修正模拟数据和语法）
const fetchChatHistory = async () => {
  if (!props.chatId) return 
  
  loading.value = true
  try {
    // 模拟数据：id与props.chatId一致
    const res = {
      data: {
        id: props.chatId, // 关键：与父组件传递的chatId同步
        roleCard: '示例角色',
        remark: '这是一个示例备注',
        messages: [
          { sender: 'user', content: '你好，AI！', timestamp: Date.now() - 60000, audioUrl: '' },
          { sender: 'ai', content: '你好！很高兴见到你。', timestamp: Date.now() - 30000, audioUrl: 'https://www.example.com/audio1.mp3' },
          { sender: 'user', content: '你是谁？', timestamp: Date.now() - 20000, audioUrl: '' },
          { sender: 'ai', content: '我是你的AI助手。', timestamp: Date.now() - 10000, audioUrl: 'https://www.example.com/audio2.mp3' }
        ]
      }
    }

    currentChat.value = res.data
    console.log('数据已赋值：', currentChat.value) // 验证数据
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('获取聊天记录失败：', error)
  } finally {
    loading.value = false
  }
}

// 6. 滚动到底部（查看历史时定位最新消息）
const scrollToBottom = () => {
  const container = messagesContainerRef.value
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}

// 7. 时间格式化（保留核心功能）
const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 8. 音频播放（保留原逻辑）
const playAudio = (audioUrl) => {
  if (!audioUrl) {
    console.log('没有音频可播放')
    return
  }
  
  const audio = new Audio(audioUrl)
  audio.play().catch(error => {
    console.error('播放音频失败:', error)
  })
}
</script>

<style scoped>
/* 仅保留弹窗必要样式，移除冗余 */
.chat-history-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.chat-history-content {
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.role-card-info {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.role-card-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.role-card-info p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  background-color: #fafafa;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  color: #606266;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

/* 消息项基础样式 */
.message-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.user-message {
  align-items: flex-end;
}

.ai-message {
  align-items: flex-start;
}

.sender-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  padding: 0 10px;
  gap: 12px;
}

.user-message .sender-info {
  flex-direction: row-reverse;
}

.sender-name {
  font-weight: bold;
  font-size: 14px;
  color: #409EFF;
}

.user-message .sender-name {
  color: #67C23A;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  display: flex;
  max-width: 70%;
}

.user-message .message-content {
  justify-content: flex-end;
}

.ai-message .message-content {
  justify-content: flex-start;
}

/* 消息气泡与按钮样式 */
.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  word-wrap: break-word;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  max-width: 100%;
}

.message-text {
  margin: 0;
  line-height: 1.5;
  word-wrap: break-word;
}

.play-button {
  height: 28px;
  padding: 4px 10px;
  font-size: 12px;
  margin: 0;
  align-self: auto;
  white-space: nowrap;
}

/* 区分用户/AI消息样式 */
.user-message .message-bubble {
  background-color: #409EFF;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-bubble {
  background-color: white;
  color: #303133;
  border-bottom-left-radius: 4px;
}

.user-message .play-button {
  background-color: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: white;
}

.ai-message .play-button {
  background-color: #f5f5f5;
  border-color: #dcdfe6;
  color: #606266;
}
</style>